package com.monitor.listenter;

import com.monitor.common.MonitorConstants;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName NodeRegisterService
 * @Package com.monitor.listenter
 * @Description 定时任务节点注册到注册中心
 * @Author zhixingbai
 * @Create 2018/10/2915:26
 */
@Service
public class NodeRegisterService {
    private final Logger logger=LoggerFactory.getLogger(this.getClass());

    private ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(1);

    private static final Map<String, String> serviceIpMap = new HashMap<>();

    @Resource
    protected StringRedisTemplate stringRedisTemplate;

    private static String MACHINE_NAME="MACHINE_NAME";

    @PostConstruct
    public void startDataSplit() {
        scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                sendHeartBeat();
            }
        }, 1, 6, TimeUnit.SECONDS);
    }

    /**
     * 节点注册和心跳设置
     */
    public void sendHeartBeat() {
        String machineName=getMachineName();
        try {
            if(StringUtils.isEmpty(machineName)){
                logger.error("节点注册到redis注册中心未获取到应用名称");
            }else{
                //心跳写入
                stringRedisTemplate.opsForValue().set(machineName+ MonitorConstants.MACHINENAME_SUFFIX,machineName,20,TimeUnit.SECONDS);
                ////注册
                stringRedisTemplate.opsForSet().add(MonitorConstants.MACHINENAME_REG,machineName);
                logger.info("节点:{},注册到redis注册中心,心跳写入成功",machineName);
            }
        } catch (Exception e) {
            logger.error("节点:{},注册到redis注册中心出现异常：{}",machineName, e.getMessage(),e);
        }
    }

    /**
     * 获取 应用要查询的id末尾值
     * @return
     */
    public String getMachineAllotData(){
        String machineAllotData = "";
        String macheineName=getMachineName();
        try {
            machineAllotData = stringRedisTemplate.opsForValue().get(macheineName);
        } catch (Exception e) {
            logger.error("获取节点【{}】对应的分片出现异常：{}",macheineName, e.getMessage(),e);
        }
        logger.info("获取节点:{},对应的分片：{}", macheineName,machineAllotData);
        return machineAllotData;
    }

    /**
     * 获取应用名称
     * @return
     */
    public  String getMachineName(){
        String machineName=serviceIpMap.get(MACHINE_NAME);
        if(StringUtils.isEmpty(machineName)){
            machineName = System.getProperty("func_type");
            if (StringUtils.isEmpty(machineName)) {
                machineName = "unknownhost";
            }
            machineName=machineName.trim();
            serviceIpMap.put(MACHINE_NAME,machineName);
        }
        logger.info("获取节点应用名称:{}",machineName);
        return machineName;
    }
}
